package unit04.day05;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 线程池
 * 线程池主要有两个作用：
 * 1：重用线程
 * 2：控制线程数量
 * 当我的应用需要创建大量线程或发现线程会频繁的创建和销毁时
 * 就应当考虑使用线程池来维护线程
 * @author Administrator
 *
 */
public class ThreadPoolDemo {

	public static void main(String[] args) {
		//创建线程池
		ExecutorService threadPool = Executors.newFixedThreadPool(2);
		
		for(int i = 0; i < 5; i++) {
			Runnable runn = new Runnable() {

				@Override
				public void run() {
					Thread t = Thread.currentThread();
					try {
						System.out.println(t+":正在运行");
						Thread.sleep(3000);
						System.out.println(t+":停止运行");
					} catch (InterruptedException e) {
						
						System.out.println(t+":线程中断");
					}
				}
				
			};
			System.out.println("分配了一个任务");
			threadPool.execute(runn);
		}
		//立即停止线程，不等待
//		threadPool.shutdownNow();
		threadPool.shutdown();
	}

}
